import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';

@Injectable()
export class CozeApiService {
  private readonly apiUrl: string;
  private readonly apiKey: string;
  private readonly botId: string;

  constructor(private configService: ConfigService) {
    this.apiUrl = this.configService.get<string>('COZE_API_URL');
    this.apiKey = this.configService.get<string>('COZE_API_KEY');
    this.botId = this.configService.get<string>('COZE_BOT_ID');
  }

  /**
   * 发送消息到Coze API
   * @param userId 用户ID
   * @param content 消息内容
   * @param conversationId 可选的对话ID，用于继续现有对话
   * @returns Coze API的响应
   */
  async sendMessage(userId: string, content: string, conversationId?: string): Promise<any> {
    try {
      const headers = {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
      };

      const payload: any = {
        bot_id: this.botId,
        user_id: userId,
        stream: false,
        auto_save_history: true,
        additional_messages: [
          {
            role: 'user',
            content: content,
            content_type: 'text',
          },
        ],
      };

      // 如果有对话ID，添加到请求中
      if (conversationId) {
        payload.conversation_id = conversationId;
      }

      const response = await axios.post(this.apiUrl, payload, { headers });
      return response.data;
    } catch (error) {
      console.error('Coze API调用失败:', error.response?.data || error.message);
      throw new HttpException(
        '与AI助手通信失败，请稍后再试',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 获取对话历史
   * @param userId 用户ID
   * @param conversationId 对话ID
   * @returns 对话历史记录
   */
  async getConversationHistory(userId: string, conversationId: string): Promise<any> {
    try {
      const headers = {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
      };

      const response = await axios.get(
        `${this.apiUrl}/history?conversation_id=${conversationId}&user_id=${userId}`,
        { headers }
      );
      return response.data;
    } catch (error) {
      console.error('获取对话历史失败:', error.response?.data || error.message);
      throw new HttpException(
        '获取对话历史失败，请稍后再试',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}